//
//  TogetherViewController.m
//  YiqiMobile
//
//  Created by henry on 13-3-23.
//  Copyright (c) 2013年 henry. All rights reserved.
//
#import "TogetherViewController.h"
#import "Utility.h"
#import "Config.h"
#import "TogetherViewCell.h"
#import "CaogaoMainViewController.h"
#import "AppDelegate.h"
#import "HomePageViewController.h"
#import "DefineAction.h"
#import "MBProgressHUD.h"
#import "JSON.h"

@interface TogetherViewController(){


}
-(void) loadDataFromServer;//从服务器加载数据

@end

@implementation TogetherViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.view.backgroundColor=[UIColor whiteColor];
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
     self.isfirst=YES;
     self.navigationItem.titleView=[Utility getTitleView:@"一起"];
    float tableHeight=0.0f;
    if (!iPhone5) {
        tableHeight=367;
    }else{
       tableHeight=455;
    }
  
    CGRect tableViewFrame=CGRectMake(0, 0, UISCREEN_WIDTH, tableHeight);
    self.mytableView.frame=tableViewFrame;
    self.mytableView=[[UITableView alloc] initWithFrame:tableViewFrame];
     self.mytableView.separatorStyle=UITableViewCellEditingStyleNone;
    self.mytableView.delegate=self;
    self.mytableView.dataSource=self;
   // self.mytableView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:self.mytableView];
    self.arrayList=[NSMutableArray array];
        //导航栏左边按钮
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(onClickAction:) normalImage:@"pushButton_normal.png" lightedImage:@"pushButton_hover.png" frame:CGRectMake(0, 0, 35, 35) title:nil tag:PUSHMENUBUTTONTAG]];
    //导航栏右边按钮
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:[Utility customButton:self action:@selector(onClickAction:) normalImage:@"moreButton_normal.png" lightedImage:@"moreButton_hover.png" frame:CGRectMake(0, 0, 35, 35) title:nil tag:PUSHMENUBUTTONTAG+1]];
    
    
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.mytableView.bounds.size.height, self.view.frame.size.width, self.mytableView.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    [self.mytableView addSubview:_refreshHeaderView];
    [_refreshHeaderView refreshLastUpdatedDate];
    
}
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    self.hidesBottomBarWhenPushed=NO;
    [app.tabBarController hideExistingTabBar];
    app.tabBarController.tabBarView.hidden=NO;
    HomePageViewController *homePageViewController=(HomePageViewController*)[[[self.tabBarController.viewControllers objectAtIndex:0] viewControllers] objectAtIndex:0];
    homePageViewController.isShowLevelPop=YES;
    UIView *rightPopView=[self.view  viewWithTag:HOMEPAGELPV];
    [rightPopView removeFromSuperview];
    if (self.isfirst) {
         [self loadDataFromServer];
        self.isfirst=NO;
    }
}

-(IBAction)onClickAction:(id)sender{//导航顶部按钮
    HomePageViewController *homepage=(HomePageViewController*)[[[self.tabBarController.viewControllers objectAtIndex:0] viewControllers] objectAtIndex:0];
    [homepage onClickAction:sender];
}



//表视图委托
#pragma mark - Tableview datasource & delegates
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UIView *sectionView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 105)];
        UIImageView *backgroundView=[[UIImageView alloc] initWithImage:[Utility imageNamed:@"bw_topbg.png"]];
        backgroundView.frame=CGRectMake(0, 0, self.view.frame.size.width, 63);
        [sectionView addSubview:backgroundView];
        self.topLabel=[Utility detailTextLabel:CGRectMake(10, 6, self.view.frame.size.width-20, 50) andFontSize:15];
        self.topLabel.textColor=UIColorFromRGB(0x666666);
        self.topLabel.numberOfLines=2;
        self.topLabel.text=[NSString stringWithFormat:@"参加的%d个圈子总共有%d篇草稿在创作中,欢迎投稿.",self
                            .quanziCount,self.caogaoCount];
        [backgroundView addSubview:self.topLabel];
        
        UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 63, 320, 42)];
        imageView.image=[Utility imageNamed:@"bw_zhuchi.png"];
        [sectionView addSubview:imageView];
        return sectionView;
    }else  if (section==1){
         UIImageView *view=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 42)];
        view.image=[Utility imageNamed:@"bw_canyu.png"];
         return  view;
    }else if (section==2){
         UIImageView *view=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 42)];
        view.image=[Utility imageNamed:@"bw_other.png"];
         return  view;
    }
    return nil;
}

//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.arrayList count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.arrayList objectAtIndex:section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
        return 105;
    }
    return 42.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 42.0f;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentity = @"togetherViewCell";
    
    TogetherViewCell *cell = (TogetherViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity];
    if (cell ==  nil) {
        cell = [[TogetherViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
    }
     NSDictionary *dict = [[self.arrayList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    cell.content.text=[dict objectForKey:@"str2"];
    cell.detail.text=[NSString stringWithFormat:@"供稿:%@  评论%@",[dict objectForKey:@"count7"],[dict objectForKey:@"count5"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CaogaoMainViewController *caogaoMainViewController=[[CaogaoMainViewController alloc] initWithNibName:nil bundle:nil];
    [caogaoMainViewController initData:[[self.arrayList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    caogaoMainViewController.hidesBottomBarWhenPushed=YES;
    [app.tabBarController hideExistingTabBar];
    app.tabBarController.tabBarView.hidden=YES;
    [self.navigationController  pushViewController:caogaoMainViewController animated:YES];
    
}

-(void) loadDataFromServer{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
      NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@",[Utility  getServerUrl],ALLCAOGAOCTION,userId];
    [self.arrayList removeAllObjects];
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
    [[MBProgressHUD showHUDAddedTo:self.tabBarController.view  animated:NO] setDetailsLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    [MBProgressHUD hideAllHUDsForView:self.tabBarController.view animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            
            if ([[result objectForKey:@"method"] isEqualToString:ALLCAOGAOCTION]) {
                    NSArray *array=[[result objectForKey:@"data"] objectForKey:@"nrList"];
                    NSInteger count=0;
                    if (array&&array.count>0) {
                        [self.arrayList addObject:array];
                        count=count+array.count;
                    }else{
                       [self.arrayList addObject:[NSMutableArray array]];
                    }
                    NSArray *array1=[[result objectForKey:@"data"] objectForKey:@"nrList1"];
                    if (array1&&array1.count>0) {
                        [self.arrayList addObject:array1];
                        count=count+array1.count;
                    }else{
                        [self.arrayList addObject:[NSMutableArray array]];
                    }
                    NSArray *array2=[[result objectForKey:@"data"] objectForKey:@"nrList2"];
                    if (array2&&array2.count>0) {
                        [self.arrayList addObject:array2];
                        count=count+array1.count;
                    }else{
                        [self.arrayList addObject:[NSMutableArray array]];
                    }
                     self.caogaoCount=count;
                    [self.mytableView reloadData];
                    NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
                    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&u.u0=%@",[Utility  getServerUrl],GETUSERINFOACTION,userId,userId];
                    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
                   [[MBProgressHUD showHUDAddedTo:self.tabBarController.view  animated:NO] setDetailsLabelText:LOADING_TITLE_DEFAULT];
                    [self.request startLoadData];
               
            }else if([[result objectForKey:@"method"] isEqualToString:GETUSERINFOACTION]){
                self.quanziCount=[[[result objectForKey:@"data"]objectForKey:@"count2"] integerValue];
                [self.mytableView reloadData];
            }
            
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
  [self doneLoadingTableViewData];
}

- (void)requestFailed:(id)context error:(NSString *)error{
      [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


// 在iOS6下已废弃
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation==UIInterfaceOrientationPortrait;
}


// Only on iOS6
- (BOOL)shouldAutorotate
{
    return NO;
}
// Only on iOS6
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)reloadTableViewDataSource{
    _reloading = YES;
    [self loadDataFromServer];
    [self.mytableView reloadData];
    
    
    
}
- (void)doneLoadingTableViewData{
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.mytableView];
    
    
}
#pragma mark –
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark –
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    
    
    
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

-(void) dealloc{
    //_mytableView.dataSource=nil;
   // _mytableView.delegate=nil;
}

@end
